package com.bootdo.common.shiro;

import com.bootdo.common.config.Constant;
import com.bootdo.common.domain.DictDO;
import com.bootdo.common.utils.DictUtils;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * 手机号登陆
 *
 * @author zhouxm
 */
public class MobileRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MobileToken token = null;
        if (authenticationToken instanceof MobileToken) {
            token = (MobileToken) authenticationToken;
        } else {
            return null;
        }
        String mobile = (String) token.getPrincipal();
        UserDO userDO = userService.getByMobile(mobile);
        if (userDO == null) {
            // 如果用户为空，表示注册，往数据库插入用户
            userDO = new UserDO();
            userDO.setUsername(mobile);
            userDO.setMobile(mobile);
            userDO.setStatus(1);
            userDO.setGmtCreate(new Date());
            userService.save(userDO);
        }
        return new SimpleAuthenticationInfo(userDO, mobile, this.getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof MobileToken;
    }
}
